<!--  -->
<template>
    <div class="overflow-hidden">
        <div data-tauri-drag-region class="titlebar bg-gradient-to-br from-black to-gray-600">
            <div data-tauri-drag-region style="
          margin-right: auto;
          display: inline-flex;
          justify-content: center;
          align-items: center;
          margin-left: 10px;
          font-size: 10pt;
        ">
                {{ info }}
            </div>
            <div class="titlebar-button" id="titlebar-minimize">
                <el-icon>
                    <Minus />
                </el-icon>
            </div>
            <div class="titlebar-button" id="titlebar-maximize">
                <el-icon>
                    <Plus />
                </el-icon>
            </div>
            <div class="titlebar-button" id="titlebar-close">
                <el-icon>
                    <Close />
                </el-icon>
            </div>
        </div>
        <div v-if="activeFile.name.endsWith('.png') || activeFile.name.endsWith('.jpg')" class=" mt-6">
            <img :src="activeFile.url" alt="预览图片" style="width: 100%; height: auto" />
        </div>
        <div v-else-if="activeFile.name.endsWith('.mp4')" class=" mt-6">
            <video controls :src="activeFile.url" style="width: auto; height: 100vh; margin: 0 auto"></video>
        </div>
        <div v-else-if="activeFile.name.endsWith('.mp3')" class=" mt-6">
            <audio controls :src="activeFile.url"></audio>
        </div>
        <div v-else-if="activeFile.name.endsWith('.js')" v-highlight class=" mt-6">


            <pre style="width: 100vw; height: 95vh; overflow: auto" v-if="activeFile.name != ''">
            <code class="text-gray-200 language-javascript hljs">
            {{ activeFile.content }}
            </code>
            </pre>
        </div>
        <div v-else-if="activeFile.name.endsWith('.css')" v-highlight class=" mt-6">


            <pre style="width: 100vw; height: 95vh; overflow: auto" v-if="activeFile.name != ''">
            <code class="text-gray-200 language-css hljs">
            {{ activeFile.content }}
            </code>
            </pre>
        </div>
        <div v-else-if="activeFile.name.endsWith('.html')" v-highlight class=" mt-6">


            <pre style="width: 100vw; height: 95vh; overflow: auto" v-if="activeFile.name != ''">
            <code class="text-gray-200 language-html hljs">
            {{ activeFile.content }}
            </code>
            </pre>
        </div>
        <div v-else-if="activeFile.name.endsWith('.pdf')">
            <embed :src="activeFile.url" type="application/pdf" style="width: 100%; height: 95vh" />
        </div>
        <div v-else-if="activeFile.name.endsWith('.xlsx')" class="overflow-hidden mt-6">
            <div style="width: 100%; height: 95vh" id="excel"></div>
        </div>
        <div v-else-if="activeFile.name.endsWith('.docx')" class="overflow-hidden mt-6">
            <div style="width: 100%; height: 95vh" id="docx"></div>
        </div>
        <div v-else-if="activeFile.name.endsWith('.json')" class="overflow-hidden mt-6">

            <json-viewer :value="activeFile.content" copyable boxed sort />



        </div>
        <div v-else class="text-black">
            <div v-loading="loading" style="width: 100%; height: 95vh"></div>

        </div>

    </div>
</template>

<script>
import { appWindow, WebviewWindow } from "@tauri-apps/api/window";
import { emit, listen } from "@tauri-apps/api/event";
import Hljs from "highlight.js";
import "highlight.js/styles/atom-one-dark.min.css";
import jsPreviewExcel from "@js-preview/excel";
import '@js-preview/excel/lib/index.css';
//引入相关样式
import jsPreviewDocx from "@js-preview/docx";
import '@js-preview/docx/lib/index.css'



import COS from "cos-js-sdk-v5";
// 存储桶名称，由 bucketname-appid 组成，appid 必须填入，可以在 COS 控制台查看存储桶名称。 https://console.cloud.tencent.com/cos5/bucket
const Bucket = import.meta.env.VITE_COS_Bucket; /* 存储桶，必须字段 */

// 存储桶 region 可以在 COS 控制台指定存储桶的概览页查看 https://console.cloud.tencent.com/cos5/bucket/
// 关于地域的详情见 https://cloud.tencent.com/document/product/436/6224
const Region = import.meta.env.VITE_COS_Region; /* 存储桶所在地域，必须字段 */

var cos = new COS({
    SecretId: import.meta.env.VITE_COS_SecretId,
    SecretKey: import.meta.env.VITE_COS_SecretKey,
});
export default {
    data() {
        return {
            activeFile: {
                name: "",
                url: "",
            },
            info: "",
            loading: true
        };
    },

    components: {},

    computed: {},

    mounted() {
        document
            .getElementById("titlebar-minimize")
            .addEventListener("click", () => appWindow.minimize());
        document
            .getElementById("titlebar-maximize")
            .addEventListener("click", () => appWindow.toggleMaximize());
        document
            .getElementById("titlebar-close")
            .addEventListener("click", () => {

                emit("cos", { data: this.activeFile });

                appWindow.close()

            });
        //console.log(this.getUrlParams());
        const label = this.$route.query.label;

        console.log(label);
        listen(label, (event) => {
            this.activeFile = event.payload.data;
            this.info = this.activeFile.name;
            console.log(this.activeFile.content);
            //Hljs.highlightAll()
            setTimeout(() => {
                this.loading = false;

                Hljs.highlightAll();
                console.log(this.activeFile.content);
                if (this.activeFile.name.endsWith('.xlsx')) {
                    console.log(this.activeFile.name);
                    const myExcelPreviewer = jsPreviewExcel.init(document.getElementById('excel'));
                    console.log(myExcelPreviewer);
                    myExcelPreviewer.preview(this.activeFile.url).then(res => {
                        console.log('预览完成');
                    }).catch(e => {
                        console.log('预览失败', e);
                    })
                }
                else if (this.activeFile.name.endsWith('.docx')) {
                    const myDocxPreviewer = jsPreviewDocx.init(document.getElementById('docx'));

                    //传递要预览的文件地址即可
                    myDocxPreviewer.preview(this.activeFile.url).then(res => {
                        console.log('预览完成');
                    }).catch(e => {
                        console.log('预览失败', e);
                    })
                }
            }, 1000); // 例如延迟1秒
        });


    },

    created() { },

    methods: {
        async getContent() {
            if (
                this.activeFile.name.toString().endsWith(".js") ||
                this.activeFile.name.toString().endsWith(".css") ||
                this.activeFile.name.toString().endsWith(".html")
            ) {
                this.activeFile.content = await this.f(this.activeFile.name);
            }
        },
        f(key) {
            return new Promise((resolve, reject) => {
                cos.getObject(
                    {
                        Bucket: Bucket,
                        Region: Bucket,

                        Key: key,
                    },
                    (err, data) => {
                        if (err) {
                            console.error(err);
                            reject(err);
                        } else {
                            console.log(data);
                            resolve(data.Body);
                        }
                    }
                );
            });
        },
        getUrlParams() {
            console.log(this.$route.query);
            const query = window.location.search.substring(1);

            return JSON.parse(
                '{"' +
                decodeURI(query)
                    .replace(/"/g, '\\"')
                    .replace(/&/g, '","')
                    .replace(/=/g, '":"') +
                '"}'
            );
        },
        highlightCode(code, language) {
            if (!language || !hljs.getLanguage(language)) {
                // 如果未指定语言或者语言不支持，则使用自动检测语言功能
                return hljs.highlightAuto(code).value;
            }
            return hljs.highlight(code, { language }).value;
        },
        getFileLanguage(filename) {
            console.log("filename: ", filename);
            if (filename.endsWith(".js")) {
                return "javascript";
            } else if (filename.endsWith(".css")) {
                return "css";
            } else if (filename.endsWith(".html")) {
                return "html";
            } else {
                return "text";
            }
            return "";
        },
    },
};
</script>
<style lang="scss" scoped>
.hljs {
    position: absolute;
    width: 100%;
    left: 30px;
    top: 0px;
    padding: 0px;
    color: #abb2bf;
    font-weight: 200;
    font-size: 0.75rem;
    font-family: Menlo, Monaco, Consolas, Courier, monospace;

    white-space: pre-wrap;
    border: 0;
}

.hljs ol {
    margin: 0 0 0 35px;
    padding: 0;
    list-style-type: decimal;
}

.hljs ol li {
    // padding: 5px;
    // padding-left: 10px;
    color: #abb2bf;
    white-space: pre;
    // list-style: decimal-leading-zero;
    list-style-position: outside;
    border-left: 1px solid #c5c5c5;
}
</style>
